package com.mstore.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;
import com.alipay.util.UtilDate;
import com.csvreader.CsvWriter;
import com.mstore.config.Constants;
import com.mstore.pojo.Account;
import com.mstore.pojo.Balance;
import com.mstore.pojo.BaseMember;
import com.mstore.pojo.Consume;
import com.mstore.pojo.Goods;
import com.mstore.pojo.Member;
import com.mstore.pojo.Shop;
import com.mstore.pojo.Tariff;
import com.mstore.pojo.User;
import com.mstore.service.AccountService;
import com.mstore.service.BalanceService;
import com.mstore.service.BaseMemberService;
import com.mstore.service.ConsumeService;
import com.mstore.service.GoodsService;
import com.mstore.service.MemberService;
import com.mstore.service.ScoreService;
import com.mstore.service.ShopService;
import com.mstore.service.TariffService;
import com.mstore.service.UserService;
import com.opensymphony.xwork2.ActionContext;

/**
 * 充值信息
 */
public class BalanceAction extends BaseAction implements SessionAware,
		ServletResponseAware {

	private static final long serialVersionUID = 1447628567801592477L;

	private BalanceService balanceService;

	private ShopService shopService;

	private MemberService memberService;

	private UserService userService;

	private ScoreService scoreService;

	private ConsumeService consumeService;

	private BaseMemberService baseMemberService;

	private GoodsService goodsService;

	private TariffService tariffService;

	private AccountService accountService;

	private Balance balance;

	private Consume consume;

	private Member member;

	private int line;

	private int index;

	private int page;

	private String result;

	private List<Balance> balances;

	private List<Consume> consumes;

	private String shopName;

	private Map<String, Object> session;

	private HttpServletResponse response;

	private double yearConsume;

	private double monthConsume;

	private double dayConsume;

	private List<Shop> shops;

	private String beginTime;

	private String endTime;

	private double timeMoney;

	private BaseMember baseMember;

	private Long memberId;

	private Long baseMemberId;

	private List<Goods> goods;

	private Long goodId;

	private List<Tariff> tariffs;

	private Tariff tariff;

	private Shop shop;

	private Long shopId;

	private User user;

	private Long userId;

	private List<Account> accounts;

	private static Logger logger = Logger.getLogger(BalanceAction.class
			.getName());

	/**
	 * 查询充值记录
	 */
	public String watchEnterpriseBalance() {
		Object object = session.get("account");
		if (object == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}
		Account account = (Account) object;

		if (balance == null) {
			balance = new Balance();
		}
		balance.setEaId(account.getId());

		int pagetemp = balanceService.getBalancesByRequireCount(balance);
		if (pagetemp == 0) {
			pagetemp = 1;
		}
		if (pagetemp % 14 == 0) {
			page = pagetemp / 14;
		}
		else {
			page = (pagetemp / 14) + 1;
		}
		if (index < 1) {
			index = 1;
		}
		else if (index > page) {
			index = page;
		}
		balances = balanceService.getBalancesByRequirePage(index, balance);

		// 充值统计
		String day = getDateInfo();
		List<Object> objList = new ArrayList<Object>();
		List<Balance> balanceList = balanceService
				.getEnterpriseBalances(balance);
		for (Balance balance : balanceList) {
			objList.add(balance);
		}
		yearConsume = getYearConsume(day, objList);
		monthConsume = getMonthConsume(day, objList);
		dayConsume = getDayConsume(day, objList);

		// 获取所有店铺
		shops = findAllShop(account);

		return "getAllBalance";
	}

	/**
	 * 将充值记录导出为csv文件
	 */
	public String exportBalances() {
		try {
			Object object = session.get("account");
			if (object == null) {
				result = "系统异常，请重新登陆！";
				return "error";
			}
			Account account = (Account) object;

			if (balance == null) {
				balance = new Balance();
			}
			balance.setEaId(account.getId());

			// 在服务器端生成CSV文件
			String csvPath = "/usr/local/csvUpload/wumicsv"
					+ System.currentTimeMillis() + ".csv";
			List<String[]> contents = new ArrayList<String[]>();
			contents.add(new String[] { "充值时间", "会员手机", "会员姓名", "公司名称", "店铺名称",
					"充值方式", "充值金额", "实际到账金额" });
			List<Balance> balanceList = balanceService
					.getBalancesByRequire(balance);
			String createTime = null;
			Double balanceSum = 0d; // 充值总额
			Double balanceDirectSum = 0d; // 实际到账总额
			Double money = 0d;
			Double directPayMoney = 0d;
			for (Balance balance : balanceList) {
				createTime = balance.getCreateTime();
				if (StringUtils.isNotBlank(createTime)) {
					createTime = createTime.substring(0,
							createTime.indexOf("."));
				}

				money = balance.getMoney();
				directPayMoney = balance.getDirectPayMoney();

				contents.add(new String[] {
						createTime,
						balance.getMemberMobile(),
						balance.getMemberName(),
						balance.getEaName(),
						balance.getShopName(),
						balance.getType() == 1 ? "现金" : "支付宝",
						money.toString(),
						balance.getType() == 1 ? money.toString()
								: directPayMoney.toString() });

				balanceSum += money;
				if (balance.getType() == 1) {
					balanceDirectSum += money;
				}
				else if (balance.getType() == 2) {
					balanceDirectSum += directPayMoney;
				}
			}
			CsvWriter wr = new CsvWriter(csvPath, ',', Charset.forName("GBK"));
			for (String[] strings : contents) {
				wr.writeRecord(strings);
			}
			wr.writeRecord(new String[] { "", "", "", "", "", "", "", "" });
			wr.writeRecord(new String[] { "充值总额", "实际到账总额" });
			wr.writeRecord(new String[] { balanceSum.toString(),
					balanceDirectSum.toString() });
			wr.close();

			// 下载CSV文件
			// 创建file对象
			File file = new File(csvPath);
			// 设置response的编码方式
			response.setContentType("application/x-msdownload;charset=utf-8");
			// 写明要下载的文件的大小
			response.setContentLength((int) file.length());

			// 设置附加文件名
			response.setHeader("Content-Disposition",
					"attachment;filename=balances.csv");

			// 读出文件到i/o流
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream buff = new BufferedInputStream(fis);

			byte[] b = new byte[1024];// 相当于我们的缓存

			long k = 0;// 该值用于计算当前实际下载了多少字节

			// 从response对象中得到输出流,准备下载
			OutputStream myout = response.getOutputStream();

			// 开始循环下载
			while (k < file.length()) {
				int j = buff.read(b, 0, 1024);
				k += j;
				// 将b中的数据写到客户端的内存
				myout.write(b, 0, j);
			}

			// 将写入到客户端的内存的数据,刷新到磁盘
			myout.flush();

			// 最后删除文件
			if (file.isFile() && file.exists()) {
				file.delete();
			}
		}
		catch (Exception e) {
			logger.error("充值记录导出报错", e);
		}

		ActionContext.getContext().getActionInvocation().getProxy()
				.setExecuteResult(false);
		return NONE;
	}

	/**
	 * 跳转到超级管理员充值对账页面
	 */
	public String goToSuperAdminDirectCSV() {
		accounts = accountService.tmpGetAll();
		List<Account> removeIndex = new ArrayList<Account>();
		for (Account account : accounts) {
			if (StringUtils.isBlank(account.getName())) {
				removeIndex.add(account);
			}
		}
		for (Account account : removeIndex) {
			accounts.remove(account);
		}
		return "goToSuperAdminDirectCSV";
	}

	/**
	 * 超级管理员导出充值账单
	 */
	public void exportSuperAdminBalanceCSV() {
		// 在服务器端生成CSV文件
		try {
			if (balance == null) {
				balance = new Balance();
			}
			balance.setType(2);
			
			String csvPath = "/usr/local/csvUpload/wumicsv"
					+ System.currentTimeMillis() + ".csv";
			List<String[]> contents = new ArrayList<String[]>();
			contents.add(new String[] { "充值时间", "会员手机", "会员姓名", "公司名称", "店铺名称",
					"充值方式", "充值金额", "实际到账金额" });
			List<Balance> balanceList = balanceService
					.getBalancesByRequire(balance);
			String createTime = null;
			Double balanceSum = 0d; // 充值总额
			Double balanceDirectSum = 0d; // 实际到账总额
			Double money = 0d;
			Double directPayMoney = 0d;
			for (Balance balance : balanceList) {
				createTime = balance.getCreateTime();
				if (StringUtils.isNotBlank(createTime)) {
					createTime = createTime.substring(0,
							createTime.indexOf("."));
				}

				money = balance.getMoney();
				directPayMoney = balance.getDirectPayMoney();

				contents.add(new String[] {
						createTime,
						balance.getMemberMobile(),
						balance.getMemberName(),
						balance.getEaName(),
						balance.getShopName(),
						balance.getType() == 1 ? "现金" : "支付宝",
						money.toString(),
						balance.getType() == 1 ? money.toString()
								: directPayMoney.toString() });

				balanceSum += money;
				if (balance.getType() == 1) {
					balanceDirectSum += money;
				}
				else if (balance.getType() == 2) {
					balanceDirectSum += directPayMoney;
				}
			}
			CsvWriter wr = new CsvWriter(csvPath, ',', Charset.forName("GBK"));
			for (String[] strings : contents) {
				wr.writeRecord(strings);
			}
			wr.writeRecord(new String[] { "", "", "", "", "", "", "", "" });
			wr.writeRecord(new String[] { "充值总额", "实际到账总额" });
			wr.writeRecord(new String[] { balanceSum.toString(),
					balanceDirectSum.toString() });
			wr.close();

			// 下载CSV文件
			// 创建file对象
			File file = new File(csvPath);
			// 设置response的编码方式
			response.setContentType("application/x-msdownload;charset=utf-8");
			// 写明要下载的文件的大小
			response.setContentLength((int) file.length());

			// 设置附加文件名
			response.setHeader("Content-Disposition",
					"attachment;filename=balances.csv");

			// 读出文件到i/o流
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream buff = new BufferedInputStream(fis);

			byte[] b = new byte[1024];// 相当于我们的缓存

			long k = 0;// 该值用于计算当前实际下载了多少字节

			// 从response对象中得到输出流,准备下载
			OutputStream myout = response.getOutputStream();

			// 开始循环下载
			while (k < file.length()) {
				int j = buff.read(b, 0, 1024);
				k += j;
				// 将b中的数据写到客户端的内存
				myout.write(b, 0, j);
			}

			// 将写入到客户端的内存的数据,刷新到磁盘
			myout.flush();

			// 最后删除文件
			if (file.isFile() && file.exists()) {
				file.delete();
			}
		}
		catch (Exception e) {
			logger.error("充值记录导出报错", e);
		}
	}

	/**
	 * 分页查询会员消费记录
	 */
	public String getAllConsumePage() {

		Object object = session.get("account");
		if (object == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}
		Account account = (Account) object;
		consume.setEaId(account.getId());

		// 根据查询条件获取充值信息
		consumes = new ArrayList<Consume>();
		if (consume.getMemberMobile() == null
				|| "".equals(consume.getMemberMobile().trim())) {
			if (consume.getShopId() == 0) {
				// 查询企业全部消费记录
				initConsumePage(1, consume);
				consumes = consumeService.getEnterpriseConsumePage(index,
						consume);
			}
			else {
				// 查询某店铺的消费记录
				initConsumePage(2, consume);
				consumes = consumeService.getConsumePage(index, consume);
			}
		}
		else {
			if (consume.getShopId() == 0) {
				// 查询某会员的消费记录
				initConsumePage(3, consume);
				consumes = consumeService.getConsumesByMobile(index, consume);
			}
			else {
				// 查询某会员在某家店铺的充值记录
				initConsumePage(4, consume);
				consumes = consumeService.getConsumesByMobileAndShop(index,
						consume);
			}
		}

		// 消费统计
		String day = getDateInfo();
		List<Consume> ConsumeList = consumeService.getConsumes(consume);
		List<Object> objList = new ArrayList<Object>();
		for (Consume consume : ConsumeList) {
			objList.add(consume);
		}
		yearConsume = getYearConsume(day, objList);
		monthConsume = getMonthConsume(day, objList);
		dayConsume = getDayConsume(day, objList);

		// 获取所有店铺
		shops = findAllShop(account);

		return "getAllConsume";
	}

	/**
	 * 年消费/充值统计
	 */
	private double getYearConsume(String day, List<Object> objList) {
		String year = day.substring(0, 4);
		String shopYear = null;

		double yearConsume = 0.0d;

		for (Object object : objList) {
			if (object instanceof Consume) {
				Consume consume = (Consume) object;
				shopYear = consume.getCreateTime().substring(0, 4);
				if (shopYear.equals(year)) {
					yearConsume += consume.getMoney();
				}
			}

			if (object instanceof Balance) {
				Balance balance = (Balance) object;
				shopYear = balance.getCreateTime().substring(0, 4);
				if (shopYear.equals(year)) {
					yearConsume += balance.getMoney();
				}
			}
		}

		BigDecimal decimal = new BigDecimal(yearConsume);
		yearConsume = decimal.setScale(1, BigDecimal.ROUND_HALF_EVEN)
				.doubleValue();

		return yearConsume;
	}

	/**
	 * 月消费/充值统计
	 */
	private double getMonthConsume(String day, List<Object> objList) {
		String month = day.substring(0, 7);
		String shopMonth = null;

		double monthConsume = 0.0d;

		for (Object object : objList) {
			if (object instanceof Consume) {
				Consume consume = (Consume) object;
				shopMonth = consume.getCreateTime().substring(0, 7);
				if (shopMonth.equals(month)) {
					monthConsume += consume.getMoney();
				}
			}

			if (object instanceof Balance) {
				Balance balance = (Balance) object;
				shopMonth = balance.getCreateTime().substring(0, 7);
				if (shopMonth.equals(month)) {
					monthConsume += balance.getMoney();
				}
			}
		}

		BigDecimal decimal = new BigDecimal(monthConsume);
		monthConsume = decimal.setScale(1, BigDecimal.ROUND_HALF_EVEN)
				.doubleValue();

		return monthConsume;
	}

	/**
	 * 日消费/充值统计
	 */
	private double getDayConsume(String day, List<Object> objList) {
		String shopDay = null;

		double dayConsume = 0.0d;

		for (Object object : objList) {
			if (object instanceof Consume) {
				Consume consume = (Consume) object;
				shopDay = consume.getCreateTime().substring(0, 10);
				if (shopDay.equals(day)) {
					dayConsume += consume.getMoney();
				}
			}

			if (object instanceof Balance) {
				Balance balance = (Balance) object;
				shopDay = balance.getCreateTime().substring(0, 10);
				if (shopDay.equals(day)) {
					dayConsume += balance.getMoney();
				}
			}
		}

		BigDecimal decimal = new BigDecimal(dayConsume);
		dayConsume = decimal.setScale(1, BigDecimal.ROUND_HALF_EVEN)
				.doubleValue();

		return dayConsume;
	}

	/**
	 * 获取日期
	 */
	private String getDateInfo() {
		Date date = new Date();
		SimpleDateFormat dateFrom = new SimpleDateFormat("yyyy-MM-dd");
		return dateFrom.format(date);
	}

	/**
	 * 获取企业所有的店铺
	 */
	private List<Shop> findAllShop(Account account) {
		Shop shop = new Shop();
		shop.setEaId(account.getId());
		return shopService.getAllShop(shop);
	}

	/**
	 * 设置充值记录的当前页数
	 */
	public void initBalancePage(int type, Balance balance) {
		int pagetemp = 1;
		switch (type) {
			case 1:
				pagetemp = balanceService.getEnterpriseBalanceLine(balance);
				break;
			case 2:
				pagetemp = balanceService.getBalanceLine(balance);
				break;
			case 3:
				pagetemp = balanceService.getEnterpriseOneBalanceLine(balance);
				break;
			case 4:
				pagetemp = balanceService.getOneBalanceLine(balance);
				break;
		}

		if (pagetemp == 0) {
			pagetemp = 1;
		}
		if (pagetemp % 14 == 0) {
			page = pagetemp / 14;
		}
		else {
			page = (pagetemp / 14) + 1;
		}
		if (index < 1) {
			index = 1;
		}
		else if (index > page) {
			index = page;
		}
	}

	/**
	 * 设置消费记录的当前页数
	 */
	public void initConsumePage(int type, Consume consume) {
		int pagetemp = 1;
		switch (type) {
			case 1:
				// 查询企业的消费记录条数
				pagetemp = consumeService.getEnterpriseConsumeLine(consume);
				break;
			case 2:
				// 查询某店铺的消费记录条数
				pagetemp = consumeService.getConsumeLine(consume);
				break;
			case 3:
				// 查询会员的消费记录条数
				pagetemp = consumeService.getOneConsumeLineByMobile(consume);
				break;
			case 4:
				// 查询会员的在某店铺消费记录条数
				pagetemp = consumeService
						.getOneConsumeLineByMobileAndShop(consume);
				break;
		}

		if (pagetemp == 0) {
			pagetemp = 1;
		}
		if (pagetemp % 14 == 0) {
			page = pagetemp / 14;
		}
		else {
			page = (pagetemp / 14) + 1;
		}
		if (index < 1) {
			index = 1;
		}
		else if (index > page) {
			index = page;
		}
	}

	/**
	 * 分店查询充值记录
	 * 
	 * @return
	 */
	public String getShopBalance() {
		User user = (User) session.get("user");
		Shop shop = new Shop();
		shop.setId(user.getShopId());
		shop = shopService.getShopById(shop);
		Balance balance = new Balance();
		balance.setShopId(shop.getId());
		balance.setEaId(shop.getEaId());

		line = balanceService.getBalancePageTotal(balance, beginTime, endTime);
		if (line == 0) {
			line = 1;
		}
		if (line % 14 == 0) {
			page = line / 14;
		}
		else {
			page = (line / 14) + 1;
		}

		if (index < 1) {
			index = 1;
		}
		else if (index > page) {
			index = page;
		}
		balances = balanceService.getBalancePageByTime(index, balance,
				beginTime, endTime);

		List<Balance> BalanceList = new ArrayList<Balance>();
		BalanceList = balanceService.getBalances(balance);
		String day = getDateInfo();
		List<Object> objList = new ArrayList<Object>();
		List<Object> objects = new ArrayList<Object>();
		for (Balance b : BalanceList) {
			objList.add(b);
		}
		List<Balance> list = new ArrayList<Balance>();
		list = balanceService.getBalancePageConsumeByTime(balance, beginTime,
				endTime);
		for (Balance ba : list) {
			objects.add(ba);
		}
		timeMoney = getBalanceByTime(objects);
		yearConsume = getYearConsume(day, objList);
		monthConsume = getMonthConsume(day, objList);
		dayConsume = getDayConsume(day, objList);
		return "getShopBalance";
	}

	/**
	 * 获取指定时间段的消费金额
	 * 
	 * @return
	 */

	private double getBalanceByTime(List<Object> objList) {
		double timeBalance = 0.0d;
		for (Object object : objList) {
			if (object instanceof Consume) {
				Consume consume = (Consume) object;
				timeBalance += consume.getMoney();
			}

			if (object instanceof Balance) {
				Balance balance = (Balance) object;
				timeBalance += balance.getMoney();

			}
		}
		return timeBalance;
	}

	/**
	 * 分店查询消费记录
	 * 
	 * @return
	 */
	public String getShopConsume() {
		User user = (User) session.get("user");
		Shop shop = new Shop();
		shop.setId(user.getShopId());
		shop = shopService.getShopById(shop);
		consume = new Consume();
		consume.setShopId(shop.getId());
		consume.setEaId(shop.getEaId());
		line = consumeService.getBalancePageByTimeTotal(consume, beginTime,
				endTime);
		if (line == 0) {
			line = 1;
		}
		if (line % 14 == 0) {
			page = line / 14;
		}
		else {
			page = (line / 14) + 1;
		}

		if (index < 1) {
			index = 1;
		}
		else if (index > page) {
			index = page;
		}
		consumes = consumeService.getConsumePageByTime(index, consume,
				beginTime, endTime);
		List<Consume> consumeList = new ArrayList<Consume>();
		consumeList = consumeService.getConsumes(consume);
		String day = getDateInfo();
		List<Object> objList = new ArrayList<Object>();
		List<Object> objects = new ArrayList<Object>();
		for (Consume c : consumeList) {
			objList.add(c);
		}
		List<Consume> list = new ArrayList<Consume>();
		list = consumeService.getBalancePageConsumeByTime(consume, beginTime,
				endTime);
		for (Consume ba : list) {
			objects.add(ba);
		}
		timeMoney = getBalanceByTime(objects);
		yearConsume = getYearConsume(day, objList);
		monthConsume = getMonthConsume(day, objList);
		dayConsume = getDayConsume(day, objList);
		return "getShopConsume";
	}

	/**
	 * 跳转到支付宝充值页面
	 */
	public String goToAlipayBalance() {
		if (member == null) {
			result = "系统数据异常";
			return "error";
		}

		if (shop == null) {
			result = "系统数据异常";
			return "error";
		}

		if (shop.getId() == null) {
			result = "系统数据异常";
			return "error";
		}

		Long memberId = member.getId();
		Long eaId = member.getEaId();
		if (memberId == null || eaId == null) {
			result = "系统数据异常";
			return "error";
		}

		member = memberService.getMemberById(member);

		baseMember = baseMemberService.getOneBaseMemberByMemberIdAndEaId(
				memberId, eaId);

		goods = goodsService.getGoodsByGoodsType("充值金额");

		tariffs = new ArrayList<Tariff>();
		for (Goods good : goods) {
			Tariff tariff = tariffService.getTariffByGoodsId(good.getGoodsId());
			tariffs.add(tariff);
		}

		return "goToAlipayBalance";
	}

	/**
	 * 向支付宝网关发送扫码支付请求
	 */
	public String createAlipayBalance() {

		try {
			if (goodId == 0) {
				result = "请输入充值金额";
				return "error";
			}

			if (member == null) {
				result = "系统数据异常";
				return "error";
			}

			memberId = member.getId();

			if (memberId == null) {
				result = "系统数据异常";
				return "error";
			}

			if (shop == null) {
				result = "系统数据异常";
				return "error";
			}

			shopId = shop.getId();
			if (shopId == null) {
				result = "系统数据异常";
				return "error";
			}

			Object usr = (Object) session.get("user");
			if (usr == null) {
				result = "系统数据异常";
				return "error";
			}
			user = (User) usr;
			userId = user.getId();

			tariff = tariffService.getTariffByGoodsId(goodId);
			if (tariff == null) {
				result = "资费不存在";
				return "error";
			}

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("qrcodeImgUrl", alipayAPI());
			result = mapTojson(map);
		}
		catch (Exception e) {
			logger.error("创建发送扫码支付请求参数报错", e);
		}

		return "createAlipayBalance";
	}

	/**
	 * 组装并发送请求数据 返回支付宝商品二维码网址
	 * 
	 * @throws Exception
	 */
	private String alipayAPI() throws Exception {
		// 接口调用时间
		String timestamp = UtilDate.getDateFormatter();
		// 格式为：yyyy-MM-dd HH:mm:ss

		// 动作
		String method = "add";
		// 创建商品二维码

		// 业务类型
		String biz_type = "10";
		// 目前只支持1

		// 业务数据
		String biz_data = createBizData();
		// 格式：JSON 大字符串，详见技术文档4.2.1章节

		// ////////////////////////////////////////////////////////////////////////////////

		// 把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "alipay.mobile.qrcode.manage");
		sParaTemp.put("partner", AlipayConfig.partner);
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("timestamp", timestamp);
		sParaTemp.put("method", method);
		sParaTemp.put("biz_type", biz_type);
		sParaTemp.put("biz_data", biz_data);
		// 建立请求
		String sHtmlText = AlipaySubmit.buildRequest("", "", sParaTemp);
		// 截取qrcode_img_url
		return subStringFrom(sHtmlText, "<qrcode_img_url>", "</qrcode_img_url>");
	}

	/**
	 * 生成业务数据
	 */
	private String createBizData() {
		Map<String, Object> map = new HashMap<String, Object>();
		// 备注
		map.put("memo", "会员充值业务");
		// 放入memberId,baseMemberId

		// 扩展属性
		Map<String, Object> extInfo = new HashMap<String, Object>();
		extInfo.put("logo_name", "二维码");
		map.put("ext_info", extInfo);

		// 商品明细
		Map<String, Object> goodsInfo = new HashMap<String, Object>();
		// goodsInfo的id的组成结构
		// goodId-shopId-userId-memberId
		goodsInfo.put("id", goodId + "-" + shopId + "-" + userId + "-"
				+ memberId);
		goodsInfo.put("name", tariff.getTariffName());
		goodsInfo.put("price", floatToScale(tariff.getFee()));
		goodsInfo.put("desc", tariff.getDescription());
		map.put("goods_info", goodsInfo);

		// 是否需要收货地址
		map.put("need_address", "F");
		// 不需要

		// 交易类型
		map.put("trade_type", "1");
		// 1：即时到账 2：担保交易

		// 通知商户下单URL
		map.put("return_url", Constants.alipayGateway
				+ "/balanceorderinfoaction!createAlipayBalanceOrderInfo");

		// 通知商户支付结果URL
		map.put("notify_url", Constants.alipayGateway
				+ "/balanceorderinfoaction!createAlipayBalanceTradeInfo");

		return super.mapTojson(map);
	}

	/**
	 * float精度处理
	 */
	private String floatToScale(float value) {
		BigDecimal decimal = new BigDecimal(value);
		return ""
				+ decimal.setScale(2, BigDecimal.ROUND_HALF_EVEN).floatValue();
	}

	/**
	 * 截取2个字符串中间的字符串
	 */
	private String subStringFrom(String str, String begin, String end) {
		int beginIndex = str.indexOf(begin);
		beginIndex += begin.length();
		int endIndex = str.indexOf(end);

		return str.substring(beginIndex, endIndex);
	}

	public BalanceService getBalanceService() {
		return balanceService;
	}

	public void setBalanceService(BalanceService balanceService) {
		this.balanceService = balanceService;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public List<Balance> getBalances() {
		return balances;
	}

	public void setBalances(List<Balance> balances) {
		this.balances = balances;
	}

	public Balance getBalance() {
		return balance;
	}

	public void setBalance(Balance balance) {
		this.balance = balance;
	}

	public ShopService getShopService() {
		return shopService;
	}

	public void setShopService(ShopService shopService) {
		this.shopService = shopService;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public ScoreService getScoreService() {
		return scoreService;
	}

	public void setScoreService(ScoreService scoreService) {
		this.scoreService = scoreService;
	}

	public ConsumeService getConsumeService() {
		return consumeService;
	}

	public void setConsumeService(ConsumeService consumeService) {
		this.consumeService = consumeService;
	}

	public Consume getConsume() {
		return consume;
	}

	public void setConsume(Consume consume) {
		this.consume = consume;
	}

	public List<Consume> getConsumes() {
		return consumes;
	}

	public void setConsumes(List<Consume> consumes) {
		this.consumes = consumes;
	}

	public double getYearConsume() {
		return yearConsume;
	}

	public void setYearConsume(double yearConsume) {
		this.yearConsume = yearConsume;
	}

	public double getMonthConsume() {
		return monthConsume;
	}

	public void setMonthConsume(double monthConsume) {
		this.monthConsume = monthConsume;
	}

	public double getDayConsume() {
		return dayConsume;
	}

	public void setDayConsume(double dayConsume) {
		this.dayConsume = dayConsume;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getShopName() {
		return shopName;
	}

	public void setShopName(String shopName) {
		this.shopName = shopName;
	}

	public List<Shop> getShops() {
		return shops;
	}

	public void setShops(List<Shop> shops) {
		this.shops = shops;
	}

	public int getLine() {
		return line;
	}

	public void setLine(int line) {
		this.line = line;
	}

	public String getBeginTime() {
		return beginTime;
	}

	public void setBeginTime(String beginTime) {
		this.beginTime = beginTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public double getTimeMoney() {
		return timeMoney;
	}

	public void setTimeMoney(double timeMoney) {
		this.timeMoney = timeMoney;
	}

	public BaseMemberService getBaseMemberService() {
		return baseMemberService;
	}

	public void setBaseMemberService(BaseMemberService baseMemberService) {
		this.baseMemberService = baseMemberService;
	}

	public BaseMember getBaseMember() {
		return baseMember;
	}

	public void setBaseMember(BaseMember baseMember) {
		this.baseMember = baseMember;
	}

	public Long getGoodId() {
		return goodId;
	}

	public void setGoodId(Long goodId) {
		this.goodId = goodId;
	}

	public Long getMemberId() {
		return memberId;
	}

	public void setMemberId(Long memberId) {
		this.memberId = memberId;
	}

	public Long getBaseMemberId() {
		return baseMemberId;
	}

	public void setBaseMemberId(Long baseMemberId) {
		this.baseMemberId = baseMemberId;
	}

	public List<Goods> getGoods() {
		return goods;
	}

	public void setGoods(List<Goods> goods) {
		this.goods = goods;
	}

	public GoodsService getGoodsService() {
		return goodsService;
	}

	public void setGoodsService(GoodsService goodsService) {
		this.goodsService = goodsService;
	}

	public TariffService getTariffService() {
		return tariffService;
	}

	public void setTariffService(TariffService tariffService) {
		this.tariffService = tariffService;
	}

	public List<Tariff> getTariffs() {
		return tariffs;
	}

	public void setTariffs(List<Tariff> tariffs) {
		this.tariffs = tariffs;
	}

	public Tariff getTariff() {
		return tariff;
	}

	public void setTariff(Tariff tariff) {
		this.tariff = tariff;
	}

	public Shop getShop() {
		return shop;
	}

	public void setShop(Shop shop) {
		this.shop = shop;
	}

	public Long getShopId() {
		return shopId;
	}

	public void setShopId(Long shopId) {
		this.shopId = shopId;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public List<Account> getAccounts() {
		return accounts;
	}

	public void setAccounts(List<Account> accounts) {
		this.accounts = accounts;
	}

	public AccountService getAccountService() {
		return accountService;
	}

	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

}
